package com.lmx.persistence.service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;
import com.lmx.common.constants.CommonConstants;
import com.lmx.common.util.CommonUtil;
import com.lmx.persistence.service.common.BaseCrudServiceImpl;
import com.lmx.repoDomain.tmodel.Customer;
import com.lmx.repoDomain.tmodel.CustomerDrugProjectExe;
import com.lmx.repoDomain.tmodel.Employee;

/**
 * 用药计划执行情况service实现
 *
 * @author ytche
 * @date 2017年7月27日
 *
 */
@Service(value = "customerDrugProjectExeService")
public class CustomerDrugProjectExeServiceImpl extends
		BaseCrudServiceImpl<CustomerDrugProjectExe> implements
		CustomerDrugProjectExeService {

	@SuppressWarnings("rawtypes")
	@Autowired
	private GenericService dslJpaService;

	@Override
	public List<CustomerDrugProjectExe> find(Long tenantId,
			Map<String, String> filter) {
		String statisticTime = filter.get("statisticTime");
		Integer startTime = filter.get("type").equals(
				CommonConstants.TYPE_OR_MONTH) ? CommonUtil
				.getMonthBegin(statisticTime) : CommonUtil
				.getWeekBegin(statisticTime);
		Integer endTime = filter.get("type").equals(
				CommonConstants.TYPE_OR_MONTH) ? CommonUtil
				.getNextMonthBegin(statisticTime) : startTime + 3600 * 24 * 7;
		this.dslJpaService.setEntityClass(Customer.class);
		Customer customer = (Customer) this.dslJpaService.findOne(new Long(
				filter.get("customer.id")));
		return findExeForCustomers(tenantId, Lists.newArrayList(customer),
				startTime, endTime);
	}

	private List<CustomerDrugProjectExe> findExeForCustomers(Long tenantId,
			List<Customer> customers, Integer startTime, Integer endTime) {
		String queryStr = "from CustomerDrugProjectExe where delStatus=0 and tenant.id= :tenantId "
				+ " and customerDrug.customer in (:customers) and createDateTime >= :startTime "
				+ " and createDateTime <:endTime order by createDateTime ";
		return super.em.createQuery(queryStr)
				.setParameter("tenantId", tenantId)
				.setParameter("customers", customers)
				.setParameter("startTime", startTime)
				.setParameter("endTime", endTime).getResultList();
	}

	@Override
	public List<CustomerDrugProjectExe> findByEmployeeAndCustomer(Long tenantId,
			List<Customer> customers, Integer startTime, Integer endTime,
			Employee employee) {
		List<CustomerDrugProjectExe> rtn = this.findExeForCustomers(tenantId,
				customers, startTime, endTime);

		return rtn
				.stream()
				.filter(p -> employee.getSystemusers() != null
						&& employee.getSystemusers().contains(
								p.getLastUpdateUser()))
				.collect(Collectors.toList());
	}
}
